import axios from 'axios'
import router from '@/router'

// create an axios instance
import { Message } from 'element-ui'
import store from '@/store/index'
const service = axios.create({
  baseURL: process.env.VUE_APP_URL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  withCredentials: true
})

service.interceptors.request.use(
  (config) => {
    if (!config.noToken) {
      config.headers.token = store.state.login.token
    }

    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    console.log(response)
    if (response.data.code === 201) {
      Message.error(response.data.message)
      return Promise.reject(new Error(response.data.message))
    }
    if (response.data.code === 202) {
      console.log(response)

      Message.error(response.data.message)
      return Promise.reject(new Error())
    } else if (response.data.code === 206) {
      // 删除token，删除用户信息
      store.commit('login/delTokenInfo')
      // 提示信息
      Message.error(response.data.message)
      // 跳转到登录页面
      router.push('/login')
      return Promise.reject(new Error(response.data.message))
    } else {
      // if the custom code is not 20000, it is judged as an error.
      return response
    }
  },
  (error) => {
    // 状态码非2开头
    return Promise.reject(error)
  }
)

export default service
